package it.univaq.di.helpdesk.common.utils;

import java.io.Writer;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;

public class AjaxResponse {
	private XStream xstream = null;
	private static AjaxResponse instance = null;
	
	private AjaxResponse() {
		xstream = new XStream(new JsonHierarchicalStreamDriver(){
		    public HierarchicalStreamWriter createWriter(Writer writer) {
		        return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
		    }
		});
		//xstream.setMode(XStream.NO_REFERENCES);
		xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);
	}
	
	public static synchronized AjaxResponse getInstance()  {
		if (instance == null) {
			instance = new AjaxResponse(); 
		}
		return instance; 
	}
	
	public String sendJson(Object obj) {
		xstream.alias(obj.getClass().getCanonicalName(), obj.getClass());
		return xstream.toXML(obj);
	}
	
	public void sendJson(Object obj, Writer out) {
		xstream.alias(obj.getClass().getCanonicalName(), obj.getClass());
		xstream.toXML(obj, out);
	}
}
